//
//  OrderController.m
//  ShopDemo
//
//  Created by Sunshine on 2018/7/12.
//  Copyright © 2018年 飞扬的青春. All rights reserved.
//

#import "OrderController.h"
#import "OrderTabCell.h"
#import "OrderDetailCon.h"
#import "AddShopPLVC.h"
#import "AddressCon.h"

@interface OrderController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *listTableview;

@property(nonatomic,strong)NSMutableArray *datasoce;
@property(nonatomic,assign)NSInteger index;
@property(nonatomic,assign)NSInteger page;

@end

@implementation OrderController
-(NSMutableArray *)datasoce{
    if (!_datasoce) {
        _datasoce = [NSMutableArray arrayWithCapacity:10];
    }
    return _datasoce;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.index = 1;
    self.page = 0;
    self.datasoce = [NSMutableArray array];
    [self OrderDataDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:self.strurl]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatTableviewMethod];
    
    self.listTableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.page == 10 ) {
            self.index ++;
            if ([self.navigationItem.title isEqualToString:@"待支付"]) {
                NSString *url = [NSString stringWithFormat:@"/dashop/order/app/list.do?username=%@&status=0&CurrentPage=%ld",[UserDefault objectForKey:LogUserName],self.index];
                [self OrderDataDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:url]];
            }else if ([self.navigationItem.title isEqualToString:@"待发货"]){
                NSString *url = [NSString stringWithFormat:@"/dashop/order/app/list.do?username=%@&status=1&CurrentPage=%ld",[UserDefault objectForKey:LogUserName],self.index];
                 [self OrderDataDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:url]];
            }else if ([self.navigationItem.title isEqualToString:@"待收货"]){
                 NSString *url = [NSString stringWithFormat:@"/dashop/order/app/list.do?username=%@&status=2&CurrentPage=%ld",[UserDefault objectForKey:LogUserName],self.index];
                 [self OrderDataDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:url]];
            }else if ([self.navigationItem.title isEqualToString:@"待评价"]){
                 NSString *url = [NSString stringWithFormat:@"/dashop/order/app/list.do?username=%@&status=5&CurrentPage=%ld",[UserDefault objectForKey:LogUserName],self.index];
                 [self OrderDataDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:url]];
            }
        }else{
            [self.listTableview.mj_footer endRefreshingWithNoMoreData];
        }
    }];
}
-(void)OrderDataDataMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        [self.datasoce removeAllObjects];
        NSArray *arr = response;
        self.page = arr.count;
        for (NSDictionary *dic in arr) {
            [self.datasoce addObject:dic];
        }
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            [self.listTableview reloadData];
        }];
    } failBlock:^(NSError *error) {
        
    }];
    
}
-(void)creatTableviewMethod{
    self.listTableview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.listTableview];
    self.listTableview.dataSource = self;
    self.listTableview.delegate = self;
    [self.listTableview registerClass:[OrderTabCell class] forCellReuseIdentifier:@"onecell"];
    //分隔线
    self.listTableview.separatorStyle = UITableViewCellAccessoryNone;
    //去掉尾部多余的空白
    [self.listTableview setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];

}


#pragma mark --UITableViewDelegate,UITableViewDataSource--

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasoce.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = self.datasoce[section];
    NSArray *arr = dic[@"orderdetail"];
    return arr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderTabCell*cell = [tableView dequeueReusableCellWithIdentifier:@"onecell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *maindic = self.datasoce[indexPath.section];
    NSArray *ordarr = maindic[@"orderdetail"];
    NSDictionary *subdic = ordarr[indexPath.row];
    NSString *strurl = [MethodClass returnUrlSetStrWSDLURL:subdic[@"goods_pic"]];
    [cell.titimagevi sd_setImageWithURL:[NSURL URLWithString:strurl]];
    cell.titlab.text = [NSString stringWithFormat:@"%@",subdic[@"goods_name"]];
    cell.cklab.text = [NSString stringWithFormat:@"%@",subdic[@"attribute_detail_name"]];
    cell.pricelab.text = [NSString stringWithFormat:@"￥%@",subdic[@"goods_price"]];
    cell.pricelab.textColor = [UIColor redColor];
    cell.numlab.text = [NSString stringWithFormat:@"×%@",subdic[@"goods_count"]];
    
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120*kJLXWidthScale;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 45*kJLXWidthScale;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSDictionary *maindic = self.datasoce[section];
    UIView *heview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 45*kJLXWidthScale)];
    heview.backgroundColor = [UIColor whiteColor];
    UIView *linview = [UIView new];
    linview.backgroundColor = LineBackColor;
    [heview addSubview:linview];
    linview.sd_layout
    .topSpaceToView(heview, 0)
    .leftSpaceToView(heview, 0)
    .rightSpaceToView(heview, 0)
    .heightIs(1);
    NSDictionary *dic = self.datasoce[section];
    UILabel *datelab = [UILabel new];
    datelab.text = [NSString stringWithFormat:@"%@",dic[@"addtime"]];
    datelab.textColor = [UIColor lightGrayColor];
    datelab.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
    [heview addSubview:datelab];
    datelab.sd_layout
    .topSpaceToView(heview, 0)
    .leftSpaceToView(heview, 10*kJLXWidthScale)
    .bottomSpaceToView(heview, 1)
    .rightSpaceToView(heview, 100*kJLXWidthScale);
    
    MineButton *btn = [MineButton buttonWithType:UIButtonTypeCustom];
    btn.usinfo = maindic;
    btn.titleLabel.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
    [btn setTitle:@"订单详情>" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(orderdetailButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [heview addSubview:btn];
    btn.sd_layout
    .topSpaceToView(heview, 0)
    .bottomSpaceToView(heview, 0)
    .rightSpaceToView(heview, 0)
    .widthIs(100*kJLXWidthScale);
    
    UIView *twoline = [UIView new];
    twoline.backgroundColor = LineBackColor;
    [heview addSubview:twoline];
    twoline.sd_layout
    .bottomSpaceToView(heview, 0)
    .leftSpaceToView(heview, 0)
    .rightSpaceToView(heview, 0)
    .heightIs(1);
    
    return heview;
}

-(void)orderdetailButtonAction:(MineButton *)sender{
    OrderDetailCon *devc = [[OrderDetailCon alloc]init];
    devc.maindic = sender.usinfo;
    devc.navigationItem.title = sender.usinfo[@"goods_name"];
    [self.navigationController pushViewController:devc animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 105*kJLXWidthScale;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    NSDictionary *maindic = self.datasoce[section];
    NSArray *ordarr = maindic[@"orderdetail"];
    UIView *heview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 105*kJLXWidthScale)];
    UIView *linview = [UIView new];
    linview.backgroundColor = LineBackColor;
    [heview addSubview:linview];
    linview.sd_layout
    .topSpaceToView(heview, 0)
    .leftSpaceToView(heview, 0)
    .rightSpaceToView(heview, 0)
    .heightIs(5*kJLXWidthScale);
    
    CGFloat prnum = 0;
    for ( NSDictionary *shopdic in ordarr) {
        prnum = [shopdic[@"goods_price"] floatValue]*[shopdic[@"goods_count"] integerValue]+prnum;
    }
  
    UILabel *sumlab = [UILabel new];
    sumlab.textAlignment = NSTextAlignmentRight;
    sumlab.font = [UIFont systemFontOfSize:15*kJLXWidthScale];
    [heview addSubview:sumlab];
    sumlab.sd_layout
    .topSpaceToView(linview, 0)
    .rightSpaceToView(heview,10*kJLXWidthScale)
    .heightIs(45*kJLXWidthScale)
    .leftSpaceToView(heview, 8*kJLXWidthScale);
    
    NSString *str = [NSString stringWithFormat:@"运费：%.2f",[maindic[@"freight_price"] floatValue]];
    NSString *sumstr = [NSString stringWithFormat:@"订单合计：￥%.2f  %@",prnum,str];
    NSRange range = [sumstr rangeOfString: str];
    NSMutableAttributedString*attribute = [[NSMutableAttributedString alloc] initWithString: sumstr];
    [attribute addAttributes: @{NSForegroundColorAttributeName: [[UIColor grayColor] colorWithAlphaComponent:0.6]}range: range];
    [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor orangeColor ]}range: NSMakeRange(0, range.location)];
    [sumlab setText: sumstr];
    [sumlab setAttributedText: attribute];
    
    UIView *linview01 = [UIView new];
    linview01.backgroundColor = LineBackColor;
    [heview addSubview:linview01];
    linview01.sd_layout
    .topSpaceToView(sumlab, 0)
    .leftSpaceToView(heview, 0)
    .rightSpaceToView(heview, 0)
    .heightIs(1*kJLXWidthScale);
    if ([self.navigationItem.title isEqualToString:@"待支付"]) {
        if ([maindic[@"surplustimes"] floatValue] == 0) {
            UILabel *lab = [UILabel new];
            lab.text = @"交易关闭";
            lab.textAlignment = NSTextAlignmentRight;
            lab.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
            lab.textColor = [UIColor redColor];
            [heview addSubview:lab];
            lab.sd_layout
            .topSpaceToView(linview01, 10*kJLXWidthScale)
            .rightSpaceToView(heview, 10*kJLXWidthScale)
            .bottomSpaceToView(heview, 10*kJLXWidthScale)
            .widthIs(100*kJLXWidthScale);
        }else{
            for (int i = 0; i < 2; i ++) {
                MineButton *btn = [MineButton buttonWithType:UIButtonTypeSystem];
                btn.tag = 360+i;
                btn.usinfo = maindic;
                [btn addTarget:self action:@selector(orderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                btn.titleLabel.font = [UIFont systemFontOfSize:14*kJLXWidthScale];
                btn.layer.masksToBounds = YES;
                btn.layer.cornerRadius = 5*kJLXWidthScale;
                btn.layer.borderColor = [UIColor orangeColor].CGColor;
                btn.layer.borderWidth = 1;
                [heview addSubview:btn];
                if (i == 0) {
                    [btn setTitle:@"去支付" forState:UIControlStateNormal];
                    btn.sd_layout
                    .topSpaceToView(linview01, 10*kJLXWidthScale)
                    .rightSpaceToView(heview, 8*kJLXWidthScale)
                    .heightIs(35*kJLXWidthScale)
                    .widthIs(60*kJLXWidthScale);
                }else{
                    [btn setTitle:@"取消订单" forState:UIControlStateNormal];
                    btn.sd_layout
                    .topSpaceToView(linview01, 10*kJLXWidthScale)
                    .rightSpaceToView(heview, 85*kJLXWidthScale)
                    .heightIs(35*kJLXWidthScale)
                    .widthIs(80*kJLXWidthScale);
                }
            }
        }
    }else if ([self.navigationItem.title isEqualToString:@"待发货"]){
        UILabel *lab = [UILabel new];
        lab.text = @"待发货";
        lab.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
        lab.textColor = [UIColor redColor];
        lab.textAlignment = NSTextAlignmentRight;
        [heview addSubview:lab];
        lab.sd_layout
        .topSpaceToView(linview01, 10*kJLXWidthScale)
        .rightSpaceToView(heview, 8*kJLXWidthScale)
        .heightIs(35*kJLXWidthScale)
        .widthIs(80*kJLXWidthScale);
    }else if ([self.navigationItem.title isEqualToString:@"待收货"]){
        for (int i = 0; i < 2; i ++) {
            MineButton *btn = [MineButton buttonWithType:UIButtonTypeSystem];
            btn.tag = 390+i;
            btn.usinfo = maindic;
            [btn addTarget:self action:@selector(shouhuoorderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            btn.titleLabel.font = [UIFont systemFontOfSize:14*kJLXWidthScale];
            btn.layer.masksToBounds = YES;
            btn.layer.cornerRadius = 5*kJLXWidthScale;
            btn.layer.borderColor = [UIColor orangeColor].CGColor;
            btn.layer.borderWidth = 1;
            [heview addSubview:btn];
            if (i == 0) {
                [btn setTitle:@"确认收货" forState:UIControlStateNormal];
                btn.sd_layout
                .topSpaceToView(linview01, 10*kJLXWidthScale)
                .rightSpaceToView(heview, 8*kJLXWidthScale)
                .heightIs(35*kJLXWidthScale)
                .widthIs(80*kJLXWidthScale);
            }else{
                [btn setTitle:@"查看物流" forState:UIControlStateNormal];
                btn.sd_layout
                .topSpaceToView(linview01, 10*kJLXWidthScale)
                .rightSpaceToView(heview, 100*kJLXWidthScale)
                .heightIs(35*kJLXWidthScale)
                .widthIs(80*kJLXWidthScale);
            }
        }
    }else if ([self.navigationItem.title isEqualToString:@"待评价"]){
        
        MineButton *btn = [MineButton buttonWithType:UIButtonTypeSystem];
        btn.usinfo = maindic;
        [btn addTarget:self action:@selector(pingjiaorderButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:14*kJLXWidthScale];
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 5*kJLXWidthScale;
        btn.layer.borderColor = [UIColor orangeColor].CGColor;
        btn.layer.borderWidth = 1;
        [heview addSubview:btn];
        [btn setTitle:@"待评价" forState:UIControlStateNormal];
        btn.sd_layout
        .topSpaceToView(linview01, 10*kJLXWidthScale)
        .rightSpaceToView(heview, 8*kJLXWidthScale)
        .heightIs(35*kJLXWidthScale)
        .widthIs(60*kJLXWidthScale);
    }
    
   
    
    return heview;
}

-(void)orderButtonAction:(MineButton *)sender{
    if(sender.tag == 360){
        [self gotoPayContoller];
    }else if (sender.tag == 361) {
        NSString *strurl = [NSString stringWithFormat:@"/dashop/order/app/editStatus.do?order_id=%@&status=%@",sender.usinfo[@"order_id"],@"5"];
        NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:strurl];
        [self OrderStatesMethodWithUrl:endstr];
    } else if (sender.tag == 390) {
        
    } else if(sender.tag == 391){
        
    }
    
}

-(void)shouhuoorderButtonAction:(MineButton *)sender{
    if (sender.tag == 391) {
        NSString *strurl = [NSString stringWithFormat:@"/dashop/order/app/editStatus.do?order_id=%@&status=%@",sender.usinfo[@"order_id"],@"99"];
        NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:strurl];
        [self OrderStatesMethodWithUrl:endstr];
    }else{
        
    }
}

-(void)pingjiaorderButtonAction:(MineButton *)sender{
    AddShopPLVC *plVC = [[AddShopPLVC alloc]init];
    plVC.maindic = sender.usinfo;
    [self.navigationController pushViewController:plVC animated:YES];
}


-(void)OrderStatesMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSDictionary *dic = response;
        if ([dic[@"result"] integerValue] == 1) {
            [self OrderDataDataMethodWithUrl:[MethodClass returnUrlSetStrWSDLURL:self.strurl]];
        }
    } failBlock:^(NSError *error) {
        
    }];
    
}

-(void)gotoPayContoller{
//    NSString *shopnumstr = [NSString stringWithFormat:@"%ld",shopnum];
    AddressCon *addVC = [[AddressCon alloc]init];
//    addVC.sumPriceStr = [NSString stringWithFormat:@"%.2f",shopnum * [self.guigePrice floatValue]];
//    NSDictionary *orderdic = @{@"GOODS_PIC":imagearr[0],@"GOODS_NAME":self.maindic[@"GOODS_NAME"],@"GOODS_ATTRIBUTE":self.guigeStr,@"GOODS_PRICE":self.guigePrice};
//    addVC.seleSCarArray = @[orderdic];
//    addVC.shopId = self.shangpingId;
//    addVC.shopsxId = self.guigeId;
//    addVC.shopNumId = shopnumstr;
    addVC.payType = @"立即购买";
    addVC.hidesBottomBarWhenPushed = YES;
    addVC.successBlock = ^{
        
    };
    
//    NSString *strurl = [NSString stringWithFormat:@"/dashop/order/app/order_total.do?GOODS_ID=%@&ATTRIBUTE_DETAIL_ID=%@&GOODS_COUNT=%@&USER_ID=%@&COUPON_ID=",self.shangpingId,self.guigeId,shopnumstr,[UserDefault objectForKey:LogUserID]];
//    NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:strurl];
//    [self querenOrderMethodWithUrl:endstr];
    
    [self.navigationController pushViewController:addVC animated:YES];
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat sectionHeaderHeight = 50;
    if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y> 0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }else
        if(scrollView.contentOffset.y >= sectionHeaderHeight){
            
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
}




@end
